package org.example.gui.listener;

import org.example.gui.panel.BackupAndRecoverPanel;
import org.example.util.SQLUtil;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * BackupAndRecoverPanel 的监听器，监听按钮动作后进行导出（数据库或 Excel）操作
 */

public class BackupListener implements ActionListener {
    private final String fileSuffix;  // 例如 ".db"、".xlsx"，前面要加小数点
    public static final String DB = ".db";
    public static final String XLSX = ".xlsx";

    public BackupListener(String fileSuffix) {
        this.fileSuffix = fileSuffix;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        BackupAndRecoverPanel panel = BackupAndRecoverPanel.instance;
        //拉起文件 tally_book.db 选择器
        JFileChooser fc = new JFileChooser();
        fc.setSelectedFile(new File("tally_book" + fileSuffix));
        //定义文件类型 .db 过滤器
        fc.setFileFilter(new FileFilter() {
            @Override
            public String getDescription() {
                return fileSuffix;
            }

            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(fileSuffix);
            }
        });

        int returnVal = fc.showSaveDialog(panel);
        File file = fc.getSelectedFile();
        //捕捉是否点击保存
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            //如果保存的文件名没有以.db结尾，自动加上.db
            System.out.println(file);
            if (!file.getName().toLowerCase().endsWith(fileSuffix))
                file = new File(file.getParent(), file.getName() + fileSuffix);
            System.out.println(file);

            try {
                if (fileSuffix.equals(DB)) {
                    SQLUtil.backup(file.getAbsolutePath());
                } else if (fileSuffix.equals(XLSX)) {
                    SQLUtil.exportToExcel(file.getAbsolutePath());
                }
                JOptionPane.showMessageDialog(panel, "备份成功,备份文件位于:\r\n" + file.getAbsolutePath());
            } catch (Exception e1) {
                e1.printStackTrace();
                JOptionPane.showMessageDialog(panel, "备份失败\r\n错误:\r\n" + e1.getMessage());
            }
        }
    }
}